/**
 * File    : IfLoggedin.java
 * Created : 2008-1-2
 * By      : lhg
 */
package com.luhuiguo.tapestry5.security.components;

import java.security.Principal;

import org.apache.tapestry5.Block;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.RequestGlobals;

/**
 * @author LuHuiguo
 * @version $Id: IfLoggedIn.java 8 2008-10-18 05:06:07Z LuHuiguo $
 * 
 */
public class IfLoggedIn {
	/**
	 * Optional parameter to invert the test. If true, then the body is rendered
	 * when the test parameter is false (not true).
	 */
	@Parameter
	private boolean negate;

	/**
	 * An alternate {@link Block} to render if the test parameter is false. The
	 * default, null, means render nothing in that situation.
	 */
	@Parameter(name = "else")
	private Block elseBlock;

	@Inject
	private RequestGlobals requestGlobals;

	private boolean test() {
		Principal principal = requestGlobals.getHTTPServletRequest()
				.getUserPrincipal();
		return principal != null && principal.getName() != "";
	}

	/**
	 * Returns null if the test method returns true, which allows normal
	 * rendering (of the body). If the test parameter is false, returns the else
	 * parameter (this may also be null).
	 */
	Object beginRender() {
		if (test() != negate) {
			return null;
		} else {
			return elseBlock;
		}
	}

	/**
	 * If the test method returns true, then the body is rendered, otherwise
	 * not. The component does not have a template or do any other rendering
	 * besides its body.
	 */
	boolean beforeRenderBody() {
		return test() != negate;
	}

	void setup(String role, boolean negate, Block elseBlock) {
		this.negate = negate;
		this.elseBlock = elseBlock;
	}
}
